package com.lottery.material.controller.admin.conf;

import com.lottery.material.common.EnumInfo;
import com.lottery.material.controller.base.BaseController;
import com.lottery.material.enumeration.ResultEnum;
import com.lottery.material.enumeration.common.CommonEnum;
import com.lottery.material.enumeration.conf.MenuLevelConfigEnum;
import com.lottery.material.pojo.circle.CircleInfo;
import com.lottery.material.pojo.conf.MenuLevelConfig;
import com.lottery.material.pojo.page.Page;
import com.lottery.material.pojo.page.PageData;
import com.lottery.material.pojocustom.conf.MenuLevelConfigCustom;
import com.lottery.material.service.admin.circle.CircleInfoService;
import com.lottery.material.service.admin.conf.MenuLevelConfigService;
import com.lottery.material.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Description：二级类别配置Controller
 * Created by 朱正磊 on 2019-04-19 11:35
 */
@Slf4j
@Controller("adminMenuTwoLevelConfigController")
@RequestMapping("/admin/menuTwoLevelConfig")
public class MenuTwoLevelConfigController extends BaseController {

    //菜单地址，用于权限控制
    private String menuUrl = "admin/menuTwoLevelConfig/list";

    private final MenuLevelConfigService menuLevelConfigService;

    private final CircleInfoService circleInfoService;

    @Autowired
    public MenuTwoLevelConfigController(MenuLevelConfigService menuLevelConfigService,
                                        CircleInfoService circleInfoService) {
        this.menuLevelConfigService = menuLevelConfigService;
        this.circleInfoService = circleInfoService;
    }

    /**
     * description：分页列表
     * user 朱正磊
     * time 2019-04-17 15:06
     * @param page 分页对象
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/list")
    public ModelAndView listPage(Page page, Map<String, Object> map) {
        //分页对象设置页面请求参数
        PageData pd = getPageData();
        PdUtil.rePut(pd);
        //查询二级分类
        pd.put("levelType", MenuLevelConfigEnum.LEVEL_TYPE_TWO.getValue().toString());
        page.setPd(pd);

        //查询分页列表
        List<MenuLevelConfigCustom> list = menuLevelConfigService.findTwoCustomListPage(page);
        map.put("list", list);
        map.put("pd", pd);
        map.put("QX", Jurisdiction.getHC());

        //状态（1：上架；2：下架）
        List<EnumInfo> stateList = EnumUtil.getEnumInfoList(CommonEnum.STATE, CommonEnum.class);
        map.put("stateList", stateList);

        return new ModelAndView("conf/menuTwoLevelConfig/listPage", map);
    }

    /**
     * description：详情页面
     * user 朱正磊
     * time 2019-04-17 16:20
     * @param id 主键
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/detailPage")
    public ModelAndView detailPage(Integer id, Map<String, Object> map) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")) {//判断是否有查看权限
            return null;
        }

        //根据主键查询扩展类
        MenuLevelConfigCustom menuLevelConfig = menuLevelConfigService.findCustomById(id);
        map.put("menuLevelConfig", menuLevelConfig);

        return new ModelAndView("conf/menuTwoLevelConfig/detailPage", map);
    }

    /**
     * description：添加页面
     * user 朱正磊
     * time 2019-04-17 16:26
     * @param parentId 父类别（一级类别）ID
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/addPage")
    public ModelAndView addPage(Integer parentId, Map<String, Object> map) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {//判断是否有添加权限
            return null;
        }

        //一级类别列表展示条件：上架并且属于圈子菜单
        List<MenuLevelConfig> menuOneLevelConfigList = menuLevelConfigService.findByLevelTypeAndState(
                (Integer) MenuLevelConfigEnum.LEVEL_TYPE_ONE.getValue(),
                (Integer) CommonEnum.STATE_ON.getValue(),
                (Integer) MenuLevelConfigEnum.IS_CIRCLE_MENU_TRUE.getValue());
        map.put("menuOneLevelConfigList", menuOneLevelConfigList);

        //父类别ID
        if (AssertUtil.isNotEmpty(parentId)) { //一级类别创建而来
            map.put("parentId", parentId);
        }

        //自动生成二级类别编号
        String menuCode = menuLevelConfigService.genMenuCode((Integer) MenuLevelConfigEnum.LEVEL_TYPE_TWO.getValue());
        map.put("menuCode", menuCode);

        //是否属于圈子菜单（1：否；2：是）
        List<EnumInfo> isCircleMenuList = EnumUtil.getEnumInfoList(MenuLevelConfigEnum.IS_CIRCLE_MENU, MenuLevelConfigEnum.class);
        EnumInfo isCircleMenuEnumInfo0 = isCircleMenuList.get(0);
        EnumInfo isCircleMenuEnumInfo1 = isCircleMenuList.get(1);
        isCircleMenuList.set(0, isCircleMenuEnumInfo1);
        isCircleMenuList.set(1, isCircleMenuEnumInfo0);
        map.put("isCircleMenuList", isCircleMenuList);

        //添加请求地址
        map.put("actionUrl", "admin/menuTwoLevelConfig/add");

        return new ModelAndView("conf/menuTwoLevelConfig/editPage", map);
    }

    /**
     * description：添加
     * user 朱正磊
     * time 2019-04-17 16:39
     * @param menuLevelConfig 对象
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/add")
    public ModelAndView add(MenuLevelConfig menuLevelConfig, Map<String, Object> map) {
        Integer flag = menuLevelConfigService.addTwo(menuLevelConfig);
        if (Objects.equals(flag, 0)) { //添加失败
            throw new RuntimeException(ResultEnum.STATUS_PERSISTENT_OPERATE_SQL_FAIL.getMessage());
        } else {
            map.put("msg","success");
            return new ModelAndView("save_result", map);
        }
    }

    /**
     * description：修改页面
     * user 朱正磊
     * time 2019-04-17 16:48
     * @param id 主键
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/editPage")
    public ModelAndView editPage(Integer id, Map<String, Object> map) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {//判断是否有修改权限
            return null;
        }

        //根据主键查询扩展类
        MenuLevelConfigCustom menuLevelConfig = menuLevelConfigService.findCustomById(id);
        map.put("menuLevelConfig", menuLevelConfig);

        //一级类别列表展示条件：上架并且属于圈子菜单
        List<MenuLevelConfig> menuOneLevelConfigList = menuLevelConfigService.findByLevelTypeAndState(
                (Integer) MenuLevelConfigEnum.LEVEL_TYPE_ONE.getValue(),
                (Integer) CommonEnum.STATE_ON.getValue(),
                (Integer) MenuLevelConfigEnum.IS_CIRCLE_MENU_TRUE.getValue());
        map.put("menuOneLevelConfigList", menuOneLevelConfigList);

        //父类别ID
        Integer parentId = menuLevelConfig.getParentId();
        map.put("parentId", parentId);

        //显示类别编号
        String menuCode = menuLevelConfig.getMenuCode();
        map.put("menuCode", menuCode);

        //是否属于圈子菜单（1：否；2：是）
        List<EnumInfo> isCircleMenuList = EnumUtil.getEnumInfoList(MenuLevelConfigEnum.IS_CIRCLE_MENU, MenuLevelConfigEnum.class);
        map.put("isCircleMenuList", isCircleMenuList);

        //修改请求地址
        map.put("actionUrl", "admin/menuTwoLevelConfig/edit");

        return new ModelAndView("conf/menuTwoLevelConfig/editPage", map);
    }

    /**
     * description：修改
     * user 朱正磊
     * time 2019-04-17 16:58
     * @param menuLevelConfig 对象
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/edit")
    public ModelAndView edit(MenuLevelConfig menuLevelConfig, Map<String, Object> map) {
        menuLevelConfig.setLevelType((Integer) MenuLevelConfigEnum.LEVEL_TYPE_TWO.getValue());
        Integer flag = menuLevelConfigService.updateById(menuLevelConfig);
        if (Objects.equals(flag, 0)) { //修改失败
            throw new RuntimeException(ResultEnum.STATUS_PERSISTENT_OPERATE_SQL_FAIL.getMessage());
        } else {
            map.put("msg","success");
            return new ModelAndView("save_result", map);
        }
    }

    /**
     * description：上架或者下架
     * user 朱正磊
     * time 2019-04-21 18:58
     * @param id 主键id
     * @param state 上下架：1上架；2下架
     * @return 返回响应对象
     */
    @SuppressWarnings("Duplicates")
    @RequestMapping("/onOrOff")
    @ResponseBody
    public ResponseResult onOrOff(Integer id, Integer state) {
        MenuLevelConfig menuLevelConfig = menuLevelConfigService.findById(id);
        final String name = "该二级类别";
        if (Objects.equals(CommonEnum.STATE_ON.getValue(), state)) { //进行下架
            menuLevelConfig.setState((Integer) CommonEnum.STATE_OFF.getValue());
            Integer flag = menuLevelConfigService.updateById(menuLevelConfig);
            if (flag == 0) {
                return ResponseResult.buildFormatResult(ResultEnum.ADMIN_OFF_FAILURE, name);
            } else {
                //将上架的圈子进行下架
                flag = circleInfoService.updateBySubTypeCode(menuLevelConfig.getMenuCode());
                if (flag == 0) {
                    return ResponseResult.buildFormatResult(ResultEnum.ADMIN_OFF_FAILURE, name);
                }
            }
            return ResponseResult.buildFormatResult(ResultEnum.ADMIN_OFF_SUCCESS, name);
        } else { //进行上架
            //判断所属的一级类别有没有上架
            Integer parentId = menuLevelConfig.getParentId();
            MenuLevelConfig parent = menuLevelConfigService.findById(parentId);
            if (AssertUtil.isNotEmpty(parent)) {//有所属的一级类别
                Integer pState = parent.getState();
                if (Objects.equals(pState, CommonEnum.STATE_OFF.getValue())) {
                    return ResponseResult.buildResult(400, "请您先上架该二级类别所属的一级类别！");
                }
            }
            //正常上架
            menuLevelConfig.setState((Integer) CommonEnum.STATE_ON.getValue());
            Integer flag = menuLevelConfigService.updateById(menuLevelConfig);
            if (flag == 0) {
                return ResponseResult.buildFormatResult(ResultEnum.ADMIN_ON_FAILURE, name);
            }
            return ResponseResult.buildFormatResult(ResultEnum.ADMIN_ON_SUCCESS, name);
        }
    }

    /**
     * description：根据一级类别编号查询相应的二级类别列表
     * user 朱正磊
     * time 2019-04-23 15:34
     * @param mainTypeCode 一级类别编号
     * @param status 1：新增或者修改； 2：查询列表
     * @return 返回响应对象
     */
    @RequestMapping("/getMenuTwoLevelConfigByMainTypeCode")
    @ResponseBody
    public ResponseResult getMenuTwoLevelConfigByMainTypeCode(String mainTypeCode, Integer status) {
        try {
            if (AssertUtil.isEmpty(mainTypeCode)) { //一级类别为空
                List<MenuLevelConfig> menuTwoLevelConfigList = menuLevelConfigService.findByLevelTypeAndState(
                        (Integer) MenuLevelConfigEnum.LEVEL_TYPE_TWO.getValue(), null,
                        (Integer) MenuLevelConfigEnum.IS_CIRCLE_MENU_TRUE.getValue());
                return ResponseResult.buildSuccess(menuTwoLevelConfigList);
            }
            MenuLevelConfig parent = menuLevelConfigService.findByMenuCode(mainTypeCode);
            List<MenuLevelConfig> menuTwoLevelConfigList;
            if (Objects.equals(1, status)) { //新增或者修改（排除下架状态的二级类别）
                menuTwoLevelConfigList = menuLevelConfigService.findByParentIdAndState(parent.getId(),
                        (Integer) CommonEnum.STATE_ON.getValue());
            } else { //查询列表（保留下架状态的二级类别，即所有，上架和下架都要有）
                menuTwoLevelConfigList = menuLevelConfigService.findByParentIdAndState(parent.getId(), null);
            }
            return ResponseResult.buildSuccess(menuTwoLevelConfigList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【根据一级类别编号查询相应的二级类别列表发生异常：{}】", ExceptionUtil.logExceptionStack(e));
            return ResponseResult.buildException();
        }
    }

    /**
     * description：验证二级类别名称不能重复（不能跟圈子、一级类别、其他二级类别名称重复）
     * user 朱正磊
     * time 2019-04-25 15:20
     * @param request 请求对象
     * @return 返回响应对象
     */
    @SuppressWarnings("Duplicates")
    @RequestMapping("/validateSameName")
    @ResponseBody
    public ResponseResult validateSameName(HttpServletRequest request) {
        String name = request.getParameter("menuName");
        name = name.trim();//去两端空格
        //根据类别名称查询类别列表（可以不存在，如果存在只允许存在一条数据）
        List<MenuLevelConfig> menuLevelConfigList = menuLevelConfigService.findByMenuName(name);
        int menuLevelConfigSize = menuLevelConfigList.size();

        //根据圈子名称查询圈子列表（可以不存在，如果存在只允许存在一条数据）
        List<CircleInfo> circleInfoList = circleInfoService.findByCircleName(name);
        int circleInfoSize = circleInfoList.size();

        //如果类别或者圈子已存在一条相同名称的数据就不允许再次出现
        if (Objects.equals(circleInfoSize, 1) || Objects.equals(menuLevelConfigSize, 1)) {
            return ResponseResult.buildResult(400, "该名称已存在，请填写其他名称！");
        }

        return ResponseResult.buildResult(200);
    }

}
